<script>
import {apiGetBuyerList, apiGetSellerList, apiGetUserById, apiProductDetail, apiUpdateOrderStatus} from "@/api/api";
import ProductDetail from "@/components/productDetail.vue";

export default {
  name: "OrderList",
  components: {ProductDetail},
  data(){
    return{
      activeTab : "buyer",
      buyerOrders : [],
      sellerOrders : [],
      buyerStatus : "",
      sellerStatus: "",
      userDetail: null,
      currentDetail: null,
      dialogVisible : false,
    }
  },
  created() {
    this.loadBuyerOrders();
    this.loadSellerOrders();
  },
  methods:{
    // 获取商品信息
    viewDetail(item){
      // console.log(item)
      apiGetUserById(item.sellerId).then(res=>{
        if (res.code===200){
          this.userDetail = res.data;
        }else{
          this.$message.error(`查询用户失败 ${res.message}`);
        }
      });
      apiProductDetail({id:item.productId}).then(res => {
        if (res.code === 200){
          this.currentDetail = res.data
        }else {
          this.$message.error(`获取商品详情失败 ${res.message}`)
        }
      })
    },
    async openProduct(item) {
      this.currentDetail = null;
      this.userDetail = null;
      try {
        await this.viewDetail(item); // 等待数据加载完成
        this.dialogVisible = true;  // 再打开对话框
      } catch (error) {
        this.$message.error("加载商品详情失败");
      }
    },
    handleTabClick(tab){
      this.activeTab = tab.name
      if(tab.name === "seller"){
        this.loadSellerOrders();
      }else{
        this.loadBuyerOrders();
      }
    },
    loadBuyerOrders(){
      apiGetBuyerList().then(res=>{
        if(res.code === 200){
          this.buyerOrders = res.data.filter(order => !this.buyerStatus || order.status === this.buyerStatus)
          console.log(this.buyerOrders)
        }
      })
    },
    loadSellerOrders(){
      apiGetSellerList().then(res=>{
        if(res.code === 200){
          this.sellerOrders = res.data.filter(order => !this.sellerStatus || order.status === this.sellerStatus)
          console.log(this.sellerOrders)
        }
      })
    },
    getStatusClass(status){
      const statusMap={
        PENDING: "status-pending",
        PAID: "status-paid",
        SHIPPED: "status-shipped",
        COMPLETED: "status-completed",
        CANCELLED: "status-cancelled",
      }
      return statusMap[status] || "";
    },
    getStatusText(status){
      const statusMap={
        PENDING: "已下单",
        PAID: "已支付",
        SHIPPED: "已发货",
        COMPLETED: "已完成",
        CANCELLED: "已取消",
      }
      return statusMap[status] || "未知状态";
    },
    confirmSend(order){
      this.$confirm("确认已收到确认发货吗？", '提示', {type: "warning"}).then(
          () => {
            apiUpdateOrderStatus({orderId: order.id, status: 'SHIPPED'}).then(res=>{
              if(res.code===200){
                this.$message.success("订单状态更改成功！");
                this.loadSellerOrders();
              }else{
                this.$message.error(
                    `操作失败 ${res.message}`
                );
              }
            })
          }
      ).catch(err => {  })
    },
    confirmReceive(order){
      this.$confirm("确认已收到货物？", '提示', {type: "warning"}).then(
          () => {
            apiUpdateOrderStatus({orderId: order.id, status: 'COMPLETED'}).then(res=>{
              if(res.code===200){
                this.$message.success("订单状态更改成功！");
                this.loadBuyerOrders();
              }else{
                this.$message.error(
                    `操作失败 ${res.message}`
                );
              }
            })
          }
      ).catch(err => {  })
    },
    cancelOrder(order){
      this.$confirm("确认取消订单吗？", '提示', {type: "warning"}).then(
          () => {
            apiUpdateOrderStatus({orderId: order.id, status: 'CANCELLED'}).then(res=>{
              if(res.code===200){
                this.$message.success("订单取消成功！");
                this.loadBuyerOrders();
              }else{
                this.$message.error(
                    `操作失败 ${res.message}`
                );
              }
            })
          }
      ).catch(err => {  })
    },
    userInfo(id){
      this.$router.push({
        name: 'userinfo', // 路由名称
        params: { userId: id } // 传递参数
      })
    },
    payOrder(order){
      this.$confirm("确认支付该订单？", '提示', {type: "warning"}).then(
          () => {
            apiUpdateOrderStatus({orderId: order.id, status: 'PAID'}).then(res=>{
              if(res.code===200){
                this.$message.success("支付成功！");
                this.loadBuyerOrders();
              }else{
                this.$message.error(
                    `操作失败 ${res.message}`
                );
              }
            })
          }
      ).catch(err => {  })
    }
  }
}
</script>

<template>
  <div class="order-list-bg">
    <el-backtop target=".order-list-bg"></el-backtop>
    <el-card class="order-list-card">
        <div class="order-header">
          <h2>我的订单</h2>
          <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane label="我的购买" name="buyer">
              <div class="order-filters">
                <el-select v-model="buyerStatus" placeholder="全部状态" @change="loadBuyerOrders" clearable>
                  <el-option label="待付款" value="PENDING" />
                  <el-option label="已付款" value="PAID" />
                  <el-option label="已发货" value="SHIPPED"/>
                  <el-option label="已完成" value="COMPLETED"/>
                  <el-option label="已取消" value="CANCELLED"/>
                </el-select>
              </div>
              <div v-if="buyerOrders.length" class="order-items">
                <el-card @click.native="" shadow="hover" v-for="item in buyerOrders" :key="item.id" class="order-item">
                  <div class="order-info">
                    <div class="order-header-info">
                      <span class="order-no">订单号： {{ item.orderNo }}</span>
                      <span class="order-status" :class="getStatusClass(item.status)">状态： {{ getStatusText(item.status) }}</span>
                    </div>
                    <div class="product-info">
                      <img class="product-img" :src="item.productImage" alt="产品图片">
                      <div class="product-details">{{item.productName}}</div>
                      <div class="product-price">{{ item.productPrice }}</div>
                      <div class="seller-info " >
                        <div @click="userInfo(item.sellerId)" class="hover-underline">
                          卖家：{{ item.sellerName }}
                        </div>
                      </div>
                    </div>
                    <div class="order-actions">
                      <el-button @click.stop="payOrder(item)" size="small" v-if="item.status === 'PENDING'" type="primary">
                        立即付款
                      </el-button>
                      <el-button @click.stop="confirmReceive(item)" size="small" v-if="item.status === 'SHIPPED'" type="success">
                        确认收货
                      </el-button>
                      <el-button @click.stop="cancelOrder(item)" size="small" v-if="item.status === 'PENDING'" type="danger">
                        取消订单
                      </el-button>
                      <el-button @click.stop="openProduct(item)" class="hover-underline" size="small" type="text">
                        商品详情
                      </el-button>
                    </div>
                  </div>
                </el-card>
              </div>
              <template v-else>
                <el-col :span="24">
                  <h3 style="text-align: center; margin: 8rem 0">没有购买任何物品</h3>
                </el-col>
              </template>
            </el-tab-pane>
            <el-tab-pane label="我的出售" name="seller">
              <div class="order-filters">
                <el-select v-model="sellerStatus" placeholder="全部状态" @change="loadSellerOrders" clearable>
                  <el-option label="待付款" value="PENDING" />
                  <el-option label="已付款" value="PAID" />
                  <el-option label="已发货" value="SHIPPED"/>
                  <el-option label="已完成" value="COMPLETED"/>
                  <el-option label="已取消" value="CANCELLED"/>
                </el-select>
              </div>
              <div v-if="sellerOrders.length" class="order-items">
                <el-card @click.native="" shadow="hover" v-for="item in sellerOrders" :key="item.id" class="order-item">
                  <div class="order-info">
                    <div class="order-header-info">
                      <span class="order-no">订单号： {{ item.orderNo }}</span>
                      <span class="order-status" :class="getStatusClass(item.status)">状态： {{ getStatusText(item.status) }}</span>
                    </div>
                    <div class="product-info">
                      <img class="product-img" :src="item.productImage" alt="产品图片">
                      <div class="product-details">{{item.productName}}</div>
                      <div class="product-price">{{ item.productPrice }}</div>
                      <div class="seller-info ">
                        <div @click="userInfo(item.buyerId)" class="hover-underline">
                          买家：{{ item.buyerName }}
                        </div>
                        <div class="order-actions">
                          <el-button @click.stop="confirmSend(item)" size="small" v-if="item.status === 'PAID'" type="primary">
                            确认发货
                          </el-button>
                          <el-button @click.stop="openProduct(item)" class="hover-underline" size="small" type="text">
                            商品详情
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-card>
              </div>
              <template v-else>
                <el-col :span="24">
                  <h3 style="text-align: center; margin: 8rem 0">没有卖出任何物品</h3>
                </el-col>
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>
    </el-card>
    <el-dialog fullscreen custom-class="custom-dialog" destroy-on-close center :visible.sync="dialogVisible" title="商品详情（点击查看多图）"
               style="border-radius: 8px; scrollbar-width: none;  min-width: 400px;">
      <!--      <span>商品详情</span>-->
      <template style="padding: 0">
        <product-detail v-if="dialogVisible && currentDetail"
                        :current-detail="currentDetail" :user-detail="userDetail"/>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">

.order-list-bg {
  overflow: auto;
  background: url("@/assets/bg/bg.png") center;
  background-size: cover;
  height: 100%;
  padding: 32px 1rem;
}
.order-list-card {
  max-width: 1200px;
  margin: 0 auto;
  border-radius: 16px;
  padding: 0 24px 24px;
  cursor: pointer;
  //overflow: hidden;
  transition: all 0.3s ease; /* 平滑过渡效果 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 默认阴影 */
}

.order-header h2 {
  margin-bottom: 24px;
  color: #409EFF;
}
.order-filters {
  margin-bottom: 16px;
}
.order-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin: 1rem;
}
.order-item {
  z-index: 1000;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease; /* 平滑过渡效果 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 默认阴影 */
}
.order-item:hover {
  box-shadow: 0 2px 8px #409EFF !important; /* 悬浮时蓝色阴影 */
  transform: scale(1.01); /* 稍微放大 */
}
.order-header-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}
.order-no {
  font-weight: bold;
  color: #333;
}
.order-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}
.status-pending { background: #ffe69e; color: #856404; }
.status-paid { background: #91efff; color: #0c5460; }
.status-shipped { background: #d4edda; color: #155724; }
.status-completed { background: #aaffbe; color: #155724; }
.status-cancelled { background: #ffa3aa; color: #721c24; }
.product-info {
  display: flex;
  gap: 16px;
}
.product-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #eee;
}
.product-details {
  flex: 1;
}
.product-name {
  font-weight: bold;
  margin-bottom: 4px;
}
.product-price {
  color: #ff4073;
  font-size: 1.1rem;
  margin-bottom: 4px;
}
.seller-info, .buyer-info {
  color: #888;
  font-size: 12px;
  display: flex;
  flex-direction: column;
  align-items: end;
  justify-content: space-between;
}
.order-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
</style>